package com.atguigu.gmall.pay.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.mq.MqConst;
import com.atguigu.gmall.mq.to.OrderPayedSkuDetailTo;
import com.atguigu.gmall.mq.to.OrderPayedSuccessMessageTo;
import com.atguigu.gmall.pay.config.AppAlipayConfig;
import com.atguigu.gmall.pay.service.PayService;
import com.atguigu.gmall.pay.vo.PayParamsVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class PayServiceImpl implements PayService {

    @Autowired
    AlipayClient alipayClient;

    @Autowired
    AppAlipayConfig alipayConfig;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderFeignClient orderFeignClient;


    /**
     * vo收集到页面支付请求的核心信息
     * @param payParamsVo
     * @return
     * @throws JsonProcessingException
     * @throws AlipayApiException
     */
    @Override
    public String payOrder(PayParamsVo payParamsVo) throws JsonProcessingException, AlipayApiException {

        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayConfig.getReturn_url());
        alipayRequest.setNotifyUrl(alipayConfig.getNotify_url());

        //2、设置支付请求的请求体详情
        String strJson = new ObjectMapper().writeValueAsString(payParamsVo);
        alipayRequest.setBizContent(strJson);

        //3、调用支付宝的支付功能
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //result代表支付包返回的支付页

        //返回支付宝的支付页
        return result;
    }

    @Override
    public Boolean queryOrderPayStatus(String outTradeNo) throws AlipayApiException, JsonProcessingException {

        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        //String out_trade_no = new String(request.getParameter("WIDTQout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
        //String trade_no = new String(request.getParameter("WIDTQtrade_no").getBytes("ISO-8859-1"),"UTF-8");
        //请二选一设置

        HashMap<String, String> map = new HashMap<>();
        map.put("out_trade_no",outTradeNo);
        String strJson = new ObjectMapper().writeValueAsString(map);


        alipayRequest.setBizContent(strJson);

        //请求
        AlipayTradeQueryResponse response = alipayClient.execute(alipayRequest);
        if ("10000".equals(response.getCode()) && response.getTradeStatus().equals("TRADE_SUCCESS")){
            return true;
        }

        return false;
    }

    /**
     * 支付成功，发送消息给mq，扣库存
     * @param out_trade_no
     */
    @Override
    public void sendPaySuccessMessage(String out_trade_no) throws JsonProcessingException {

        //TODO 2、给队列发送的内容； json串
        OrderPayedSuccessMessageTo message = new OrderPayedSuccessMessageTo();
        OrderInfo orderInfo = orderFeignClient.getOrderInfoWithDetailsByOutTradeNo(out_trade_no);
        //封装订单信息
        BeanUtils.copyProperties(orderInfo,message);

        message.setOrderId(orderInfo.getId());
        message.setOrderBody(orderInfo.getOrderDetailList().get(0).getSkuName());
        message.setPaymentWay("2");//在线支付 "1"为货到付款

        //封装订单的所有商品信息
        List<OrderPayedSkuDetailTo> detailToList = new ArrayList<>();
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            OrderPayedSkuDetailTo detailTo = new OrderPayedSkuDetailTo();
            BeanUtils.copyProperties(orderDetail,detailTo);
            detailToList.add(detailTo);
        }


        message.setDetails(detailToList);

        String strJsonMessage = new ObjectMapper().writeValueAsString(message);

        //TODO 1、队列名：queue.ware.stock      需要知道哪个交换机用哪个路由键绑定了这个队列
        //发送消息给库存系统
        rabbitTemplate.convertAndSend(MqConst.EXCHANGE_DIRECT_WARE_STOCK,MqConst.ROUTING_WARE_STOCK,strJsonMessage);

    }
}
